#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   securityPatch.sh
# Version:    1.0
# Date:       2021/03/30
# Author:     laiyixin
# Email:      laiyixin@kylinos.com.cn
# History：
#             Version 1.0, 2021/03/30
# Function:   调用不同的安全加固加固程序
# In :        security testcase name(testcase dir name)
# Out:
#              0=> Success
#              1=> Fail
#              other=> TCONF
# ----------------------------------------------------------------------

## TODO : 执行前的初始化验证
## In   : $1=>testcase dir name
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
SecPatInit() {
    local testdir="$1"
    # 加载库函数
    if [ -f "./lib/secP-lib.sh" ]; then
        source ./lib/secP-lib.sh
    else
        echo "./lib/secP-lib.sh : Can't found file !"
        return 1
    fi

    # 判断目录有效性
    if [ ! -d "${testdir}" ]; then
        echo "TCONF : Can't find testcases (${testdir})"
        return ${TCONF}
    fi

    return ${TPASS}
}

## TODO : 执行测试
## In   : $1=>testcase dir name
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
SecPatRun() {
    # 测试文件目录
    local testdir="$1"
    # 测试文件路径
    local testfile=""
    local ret="${TPASS}"

    # 进入测试目录
    cd ${testdir}
    # 测试文件，通过数组保存
    local testfilelist=($(find ./ -type f | sort))

    for testfile in ${testfilelist[*]}; do
        [[ "$testfile" =~ "readme"|"swp" ]] && continue
        if [ -x "$testfile" ]; then
            echo "Start Patch Security : ${testdir}-${testfile#*/} "
            bash $testfile
            ret=$?
        else
            echo "[ TCONF ] ${testfile#*/} : No executable permissions"
            continue
        fi

        if [ $ret -eq ${TPASS} ]; then
            echo "[ TPASS ] - ${testfile#*/}"
        elif [ $ret -eq ${TFAIL} ]; then
            echo "[ TFAIL ] - ${testfile#*/}"
            break
        else
            echo "[ TCONF ] - ${testfile#*/}"
            break
        fi
    done

    return $ret
}

## TODO: 解析函数返回值
SecPatRetParse() {
    local ret=$?
    if [ $ret -ne ${TPASS} ]; then
        exit $ret
    fi
}

## TODO: SecPatMain
## In: $1=>testcase dir name
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
SecPatMain() {
    local testdir=$(basename $1)
    cd $(dirname $1)

    SecPatInit ${testdir}
    SecPatRetParse

    SecPatRun ${testdir}
    SecPatRetParse

    return ${TPASS}
}

SecPatMain $*
exit $?
